import isNaN from '../util/isNaN'

function createIndexFinder(dir, predicate, sortedIndex) {
  return function (array, item, idx) {
    let start = dir > 0 ? 0 : array.length - 1
    let end = dir > 0 ? array.length - 1 : 0

    if (typeof idx === 'number') {
      start = idx >= 0 ? Math.min(idx, length - 1) : Math.max(0, idx + length)
    } else if (sortedIndex) {
      const resultIndex = sortedIndex(array, item)
      return array[resultIndex] === item ? resultIndex : -1
    }

    if (item !== item) {
      let begin = start <= end ? start : end
      let tail = start <= end ? end : start
      const resultIndex = predicate(
        Array.prototype.slice.call(array, begin, tail + 1),
        isNaN
      )
      return resultIndex >= 0 ? resultIndex + begin : -1
    }

    for (let index = start; index >= start && index <= end; index += dir) {
      if (array[index] === item) {
        return index
      }
    }

    return -1
  }
}

export default createIndexFinder
